package chapter22;

import java.lang.annotation.*;
import java.lang.reflect.Method;

/**
 * @author lzy
 * @version v1.0
 * Create DateTime: 2019/2/26 16:30
 */
public class MethodAnnotations {

    public static void main(String[] args) throws NoSuchMethodException {
        Class<?> clazz = MethodAnnotations.class;
        Method method = clazz.getDeclaredMethod("hello", String.class, String.class);
        Annotation[][] annotations = method.getParameterAnnotations();
        for (int i = 0; i < annotations.length; i++) {
            System.out.println("annotations for parameter " + (i + 1));
            Annotation[] anno = annotations[i];
            for (Annotation annotation : anno) {
                if (annotation instanceof QueryParam) {
                    QueryParam param = (QueryParam) annotation;
                    System.out.println(param.annotationType().getSimpleName() + ":" + param.value());
                } else if (annotation instanceof DefaultValue) {
                    DefaultValue dv = (DefaultValue) annotation;
                    System.out.println(dv.annotationType().getSimpleName() + ":" + dv.value());
                }
            }
        }
    }

    public void hello(@QueryParam("action") String action, @QueryParam("sort") @DefaultValue("asc") String sort) {

    }

    @Target(ElementType.PARAMETER)
    @Retention(RetentionPolicy.RUNTIME)
    static @interface QueryParam {
        String value();
    }

    @Target(ElementType.PARAMETER)
    @Retention(RetentionPolicy.RUNTIME)
    static @interface DefaultValue {
        String value() default "";
    }
}
